package com.example.seakdreamandroid.Lullaby;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.seakdreamandroid.MusicStoryPlayerActivity;
import com.example.seakdreamandroid.R;

import java.util.List;
import java.util.Map;

public class LullabyListAdapter extends BaseAdapter {


    private Context context;
    private LayoutInflater layoutInflater;
    private List<Map<String,Object>> data;

    public LullabyListAdapter (Context context,List<Map<String,Object>> data){
        this.context = context;
        this.data = data;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (null == view){

            holder = new ViewHolder();
            view = layoutInflater.inflate(R.layout.fragment_selected_lullaby_listitem,null);
            holder.comImg = view.findViewById(R.id.lullaby_listview_item_img);
            holder.tvAuthor = view.findViewById(R.id.lullaby_listview_item_author);
            holder.tvName = view.findViewById(R.id.lullaby_listview_item_name);
            holder.tvTimes = view.findViewById(R.id.lullaby_listview_item_playsnumber);
            view.setTag(holder);
        }else{
            holder = (ViewHolder) view.getTag();
        }
        View intentButton = view.findViewById(R.id.intent_button);
        Glide.with(context).load(data.get(i).get("Img")).into(holder.comImg);
        holder.tvName.setText((String) data.get(i).get("Name"));
        holder.tvAuthor.setText((String) data.get(i).get("Author"));
        holder.tvTimes.setText((String) data.get(i).get("Times"));
        String url = (String) data.get(i).get("Url");
        String id = (String) data.get(i).get("Id");
        intentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(context, MusicStoryPlayerActivity.class);
                intent.putExtra("audioUrl",url);
                intent.putExtra("audioId",id);
                context.startActivity(intent);
            }
        });
        return view;
    }

    final static class ViewHolder{
        private ImageView comImg;
        private TextView tvName;
        private TextView tvAuthor;
        private TextView tvTimes;
    }
}
